package service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import entry.Message;
import entry.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/webSocket" , configurator = HttpSessionConfigurator.class)
public class WebSocket {
    private Session session;
    private int userId;
    private HttpSession httpSession;
    private static Map<Integer, WebSocket> webSocketmap = new ConcurrentHashMap<Integer, WebSocket>();
    private ObjectMapper objectMapper = new ObjectMapper();

    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        User user = (User)httpSession.getAttribute("user");
        if(user != null){
            this.session = session;
            this.userId = user.getUserId();
            this.httpSession = httpSession;
            webSocketmap.put(userId, this);
        }else{
            //用户未登陆
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @OnClose
    public void onClose(){
        webSocketmap.remove(userId);
    }
    @OnMessage
    public void onMessage(String message){
        // 收到消息
        sendMessage(message);
    }
    public void sendMessage(String msg){
        Message message = null;
        try {
            message = objectMapper.readValue(msg, Message.class);
            int from = message.getFrom();
            int to = message.getTo();
            WebSocket fromSocket = webSocketmap.get(from);
            WebSocket toSocket = webSocketmap.get(to);

            if (fromSocket != null){
                fromSocket.session.getBasicRemote().sendText(msg);
            }
            if (toSocket != null){
                toSocket.session.getBasicRemote().sendText(msg);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
